import React, { useEffect, useState } from 'react';
//引入scss
import '../../../scss/zw/LimitPlan.scss'
import axios from 'axios';
//请求
import { LimitPlan_Search, LimitPlan_add, LimitPlan_edit, LimitPlan_list } from '../../../tools/api'

//引入自定义钩子函数
//公司架构列表
import { useLimitPlanTable } from "../../../hooks/zwHooks/index";

//图标
import { SearchOutlined, PlusCircleOutlined, FormOutlined } from '@ant-design/icons';
//插件
import { Breadcrumb, Divider, Input, Button, Table,  message, Form, Modal } from 'antd';
const { Search } = Input;

function LimitPlan(props) {

    //定义组件状态
    //调用钩子函数，公司构架列表
    var [limitPlanTableList, setLimitPlanTableList] = useLimitPlanTable([])
    //新增表单框是否显示
    var [isModalOpen, setIsModalOpen] = useState(false);
    //编辑表单框是否显示
    var [isModalOpenEdit, setIsModalOpenEdit] = useState(false);
    //表格是否有loading效果
    var [loading, setLoading] = useState(false);


    //分页
    var [page, setPage] = useState(1);  ///页码
    var [total, setTotal] = useState(0);   //总数
    var [pageSize, setPageSize] = useState(10);   //每页的个数

    //定义表格选择行的key
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);

    //让列表数据更新的函数
    const update = () => {
        LimitPlan_list().then((res) => {
            // console.log(res.data);
            setLimitPlanTableList(res.data)
        })
    }

    //新增
    const onFinish = (values) => {
        // 发起添加请求
        LimitPlan_add(values).then((res) => {
            console.log(res);
            if (res.status == 201) {
                message.open({ type: 'success', content: '新增成功!' });
                //关闭新增页
                setIsModalOpen(false);
                update()
                setLoading(true)
                setTimeout(() => {
                    setLoading(false)
                }, 500);
            } else {
                message.open({ type: 'error', content: '新增失败!' });
            }
        })
    }

    //新增弹框
    const showModal = () => {
        setIsModalOpen(true);
    };
    //新增弹框的取消
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    //搜索
    const onSearch = (value) => {
        console.log(value);
        LimitPlan_Search(value).then((res) => {
            setLimitPlanTableList(res.data)
            console.log(res.data)
            update()
            setLoading(true)
            setTimeout(() => {
                setLoading(false)
            }, 500);
        })
    }

    //编辑
    var { useForm } = Form  //解构useForm
    var [form] = useForm()   //获取form实例,然后需要在表单里面绑定form
    var [customerid, setCustomerid] = useState([])

    const edit = (record) => {
        form.setFieldsValue(record)
        editshouModal()
        //一次性设置多个value进行更改
        setCustomerid(record.id)
    }
    const onFinishEdit = (values) => {
        axios.patch(`http://localhost:4000/LimitPlanTable/${customerid}`,
            {
                PowerId: values.PowerId,
                Powername: values.Powername,
                Powerlevel: values.Powerlevel,
                IncludePower: values.IncludePower
            }).then((res) => {
                console.log(res.status);

                if (res.status == 200) {
                    edithandleCancel();//弹框消失
                    message.open({ type: 'success', content: '修改成功!' });
                    update()
                    setLoading(true)
                    setTimeout(() => {
                        setLoading(false)
                    }, 500);
                } else {
                    message.open({ type: 'error', content: '修改失败!' });
                }
            })
    }

    //编辑弹框显示
    const editshouModal = () => {
        setIsModalOpenEdit(true);
    }
    //编辑弹框的取消
    const edithandleCancel = () => {
        setIsModalOpenEdit(false);
    };

    //多选框
    //当表格行的选择发生改变时执行
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    //定义columns
    const columns = [
        {
            title: '权限组编号',  //表格列的名字（显示在表头上）
            dataIndex: 'PowerId',  //数据对应的属性名
        },
        {
            title: '模板名称',
            dataIndex: 'Powername',
        },
        {
            title: '权限等级',
            dataIndex: 'Powerlevel',
        },
        {
            title: '包含权限',
            dataIndex: 'IncludePower',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <>
                    <i className="edit" onClick={() => { edit(record) }}><FormOutlined /> </i>
                </>
            ),
        },

    ];
    return (
        <div className="LimitPlan">
            <div className="LimitPlanHeader">
                <Breadcrumb>
                    <Breadcrumb.Item>权限管理</Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <a>权限分配</a>
                    </Breadcrumb.Item>
                </Breadcrumb>
            </div>
            <Divider />
            <div className="LimitPlanSearch">
                <Search placeholder="请输入模板名称" onSearch={onSearch} icon={<SearchOutlined />} enterButton="搜索" loading={loading} />
                <div className="add">
                    <Button type="primary" onClick={showModal} icon={<PlusCircleOutlined />}>
                        增加
                    </Button>
                </div>
            </div>
            <div className="LimitPlanTable">
                {/* pagination分页器，是一个对象   pagination={{ current, pageSize, total }} onChange={onChange} */}
                <Table
                    columns={columns}
                    dataSource={limitPlanTableList}
                    loading={loading}
                    pagination={{ page, pageSize, total }}
                    rowSelection={rowSelection} />
            </div>
            {/* 新增的对话框 */}
            <div className="addStaff">
                <Modal title="新增" open={isModalOpen} footer={[]} className="modal"
                >
                    {/* footer={[]} 取消底部的两个按钮 */}
                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="权限组编号"
                            name="PowerId"
                            rules={[{ required: true, message: '输入权限组编号' }]}
                        >
                            <Input placeholder='输入权限组编号' />
                        </Form.Item>
                        <Form.Item
                            label="模板名称"
                            name="Powername"
                            rules={[{ required: true, message: '输入模板名称' }]}
                        >
                            <Input placeholder='输入模板名称' />
                        </Form.Item>
                        <Form.Item
                            label="权限等级"
                            name="Powerlevel"
                            rules={[{ required: true, message: '输入权限等级' }]}
                        >
                            <Input placeholder='输入权限等级' />
                        </Form.Item>
                        <Form.Item
                            label="包含权限"
                            name="IncludePower"
                            rules={[{ required: true, message: '包含权限' }]}
                        >
                            <Input placeholder='包含权限' />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
                            <Button type="primary" htmlType="submit" className="add">增加</Button>
                        </Form.Item>
                    </Form>
                    <div className="handleCancel">
                        <Button type="primary" htmlType="submit" onClick={handleCancel}>取消</Button>
                    </div>
                </Modal>
            </div>
            {/* 编辑的对话框 */}
            <div className="addStaff">
                <Modal title="编辑" open={isModalOpenEdit} footer={[]} className="editmodal"
                >
                    {/* footer={[]} 取消底部的两个按钮 */}

                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinishEdit}
                        form={form}
                    >
                        <Form.Item
                            label="权限组编号"
                            name="PowerId"
                            rules={[{ required: true, message: '输入权限组编号' }]}
                        >
                            <Input placeholder='输入权限组编号' />
                        </Form.Item>
                        <Form.Item
                            label="模板名称"
                            name="Powername"
                            rules={[{ required: true, message: '输入模板名称' }]}
                        >
                            <Input placeholder='输入模板名称' />
                        </Form.Item>
                        <Form.Item
                            label="权限等级"
                            name="Powerlevel"
                            rules={[{ required: true, message: '输入权限等级' }]}
                        >
                            <Input placeholder='输入权限等级' />
                        </Form.Item>
                        <Form.Item
                            label="包含权限"
                            name="IncludePower"
                            rules={[{ required: true, message: '包含权限' }]}
                        >
                            <Input placeholder='包含权限' />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
                            <Button type="primary" htmlType="submit" className="editbtn">保存修改</Button>
                        </Form.Item>
                    </Form>
                    <div className="edithandleCancel">
                        <Button type="primary" htmlType="submit" onClick={edithandleCancel}>取消</Button>
                    </div>
                </Modal>
            </div>
        </div>
    );
}

export default LimitPlan;